import pymysql

from code_builder.conf import read_conf

__host = read_conf.getConfig("mysql", "host")
__port = read_conf.getConfig("mysql", "port")
__user = read_conf.getConfig("mysql", "user")
__password = read_conf.getConfig("mysql", "password")
__database = read_conf.getConfig("mysql", "db")
__charset = read_conf.getConfig("mysql", "charset")
__is_print_con_error = True


def init(host, port=3306, user=None, password=None, database=None, charset="utf8"):
    global __host
    global __port
    global __user
    global __password
    global __database
    global __charset
    if host is not None:
        __host = host
    __port = port
    if user is not None:
        __user = user
    if password is not None:
        __password = password
    if database is not None:
        __database = database
    if charset is not None:
        __charset = charset


def desc_table_list(tableNameList):
    result = []
    for i in tableNameList:
        result.append(desc_table(i))
    return result


def desc_table(tableName):
    sql = "desc " + tableName
    return execute(sql)


def show_tables():
    sql = "show tables"
    return execute(sql)


def select_table(table_name, column="*"):
    sql = "select {select_column} from {table_name}".format(select_column=column, table_name=table_name)
    return execute(sql)


def execute(sql="select version()"):
    try:
        con = pymysql.connect(host=__host, port=int(__port), user=__user, password=__password, database=__database,
                              charset=__charset)
    except pymysql.err.OperationalError:
        print("连接数据库失败，使用的连接参数为")
        print("host={host}".format(host=__host))
        print("port={port}".format(port=__port))
        print("user={user}".format(user=__user))
        print("password={password}".format(password=__password))
        print("database={database}".format(database=__database))
        print("charset={charset}".format(charset=__charset))
        return ""
    cursor = con.cursor()
    cursor.execute(sql)
    data = cursor.fetchall()
    con.close()
    return data


if __name__ == "__main__":
    print(execute("select * from user"))
